﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Department;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using MediatR;
using System.Collections.Generic;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Department
{
    /// <summary>
    /// 查询部门树状结构的中介者处理类
    /// </summary>
    public class QueryDepartmentTreeHandler : IRequestHandler<QueryDepartmentCommand, ApiResult<List<DepartmentTreeDTO>>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepo;
        private readonly IMapper mapper;

        public QueryDepartmentTreeHandler(IBaseRepository<DepartmentModel> departRepo,IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询部门树状结构的中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<List<DepartmentTreeDTO>>> Handle(QueryDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartmentTreeDTO>> result = new ApiResult<List<DepartmentTreeDTO>>();

            result.Data = GetTree(0);
            result.Code = ApiEnums.Success;
            result.Msg = "查询部门树状结构列表成功!";

            return Task.FromResult(result);
        }

        /// <summary>
        /// 使用递归查询部门树
        /// </summary>
        /// <param name="parentId">父级Id</param>
        /// <returns></returns>
        public List<DepartmentTreeDTO> GetTree(long parentId) {

            var departs = departRepo.Query().Result.Where(x => x.ParentId == parentId);
            var departDtos = mapper.Map<List<DepartmentTreeDTO>>(departs);

            foreach (var dto in departDtos) {
                dto.Children = GetTree(dto.Id);

            }
            return departDtos;

        }
    }
}
